#include <QtGui>
#include <QTabWidget>

#include "MainWindow.h"
#include "Project.h"
#include "TextureWidget.h"
#include "AddCustomGlyphDialog.h"
#include "ui_AddCharacterDialog.h"

MainWindow::MainWindow() :
    project( 0 ),
    textureWidget( 0 )
{
    createActions();
    createMenus();
    createToolBars();
    createDockWindows();
    createStatusBar();

    readSettings();

    setCurrentFile("");
    setUnifiedTitleAndToolBarOnMac( true );

    textureWidget = new TextureWidget( this );

    setCentralWidget( textureWidget );
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    if (maybeSave()) 
    {
        writeSettings();
        event->accept();
    } 
    else
    {
        event->ignore();
    }
}

void MainWindow::newFile()
{
    if (maybeSave())
    {
        QDialog
            editFontHostDialog;

        editFontDialog.setupUi( &editFontHostDialog );

        connect( editFontDialog.cancelButton, SIGNAL( clicked() ), &editFontHostDialog, SLOT( reject() ) );
        connect( editFontDialog.okButton, SIGNAL( clicked() ), &editFontHostDialog, SLOT( accept() ) );

        int result = editFontHostDialog.exec();

        if( result == QDialog::Accepted )
        {
            if( project )
            {
                project->deleteLater();
            }

            setCurrentFile("");

            QFont
                font;

            font = editFontDialog.fontComboBox->currentFont();

            project = new Project;

            if ( editFontDialog.underlineCheckbox->isChecked() )
            {
                font.setUnderline(true);
            }

            if ( editFontDialog.strikeoutCheckbox->isChecked() )
            {
                font.setStrikeOut(true);
            }

            if ( editFontDialog.outlineCheckbox->isChecked() )
            {
                project->setFontIsOultined( true );
            }

            font.setPointSize( editFontDialog.fontSizeSpinBox->value() );

            project->setFont( font );

            characterViewWidget.tableView->setModel( project );
            textureWidget->setModel( project );

            QItemSelectionModel * selectionModel = new QItemSelectionModel( project, this );

            textureWidget->setSelectionModel( selectionModel );
            characterViewWidget.tableView->setSelectionModel( selectionModel );
        }
    }

}

void MainWindow::open()
{
    if (maybeSave())
    {
        QDir 
            currentDir( currentFile );
        QString 
            fileName;

        currentDir.cdUp();
        fileName = QFileDialog::getOpenFileName(this, tr("Load project"), currentDir.path(), "*.xml" );
        
        if (!fileName.isEmpty())
        {
            loadFile(fileName);
        }
    }
}

bool MainWindow::save()
{
    if (currentFile.isEmpty())
    {
        return saveAs();
    }
    else
    {
        return saveFile(currentFile);
    }
}

bool MainWindow::saveAs()
{

    QDir 
        currentDir( currentFile );
    QString 
        fileName;

    currentDir.cdUp();
    fileName = QFileDialog::getSaveFileName(this, tr("Save project as"), currentDir.path(), "*.xml" );
    
    if ( fileName.isEmpty() )
    {
        return false;
    }
    
    return saveFile(fileName);
}

void MainWindow::about()
{
   QMessageBox::about(this, tr("About Font Shaker"),
            tr("TODO"));
}

void MainWindow::documentWasModified()
{
//    setWindowModified();
}

void MainWindow::exportToABC()
{
    QString 
        abc_file_name,
        png_file_name;
    QDir 
        currentDir( currentFile );

    currentDir.cdUp();
    
    abc_file_name = QFileDialog::getSaveFileName(this, tr("Save ABC file"), currentDir.path(), tr("ABC file (*.abc)") );

    if( abc_file_name.isEmpty() )
    {
        return;
    }

    currentDir = abc_file_name;
    currentDir.cdUp();

    png_file_name = QFileDialog::getSaveFileName(this, tr("Save texture file"), currentDir.path(), tr("png file (*.png)") );

    if( png_file_name.isEmpty() )
    {
        return;
    }

    project->saveInABCFormat( abc_file_name, png_file_name );
}

void MainWindow::editFont()
{
    
}

void MainWindow::removeCurrentSelectedRows()
{
    QModelIndexList
        selected_indices;

    if( !characterViewWidget.tableView->selectionModel() )
    {
        return;
    }

    selected_indices = characterViewWidget.tableView->selectionModel()->selectedRows();

    qSort( selected_indices );

    for( int i = selected_indices.count() - 1 ; i >= 0; i -- )
    {
        project->removeRows( selected_indices[ i ].row(), 1 );
    }
    
    characterViewWidget.tableView->selectionModel()->setCurrentIndex( project->index( 0, 0 ), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows );
}

void MainWindow::addACharacter()
{
    QDialog
        dialog;
    Ui::AddCharacterDialog
        ui_dialog;
    QIntValidator
        int_validator;

    ui_dialog.setupUi( &dialog );

    int_validator.setRange( 0, 65536 );
    ui_dialog.unicodeLineEdit->setValidator( &int_validator );

    int result = dialog.exec();

    if( result == QDialog::Accepted )
    {
        if( !ui_dialog.unicodeLineEdit->text().isEmpty() )
        {
            bool ok;

            int code = ui_dialog.unicodeLineEdit->text().toInt( &ok );

            if( ok )
            {
                project->addCharacter( code );
            }
        }

        if( !ui_dialog.characterLineEdit->text().isEmpty() )
        {
            foreach( QChar character, ui_dialog.characterLineEdit->text()  )
            {
                project->addCharacter( character.unicode() );
            }
        }
    }
}

void MainWindow::addACustomGlyph()
{
    AddCustomGlyphDialog
        dialog;

    int result = dialog.exec();

    if( result == QDialog::Accepted )
    {
        project->addCustomCharacter( dialog.unicode(), dialog.pixmap(), dialog.start(), dialog.advance(), dialog.baseline() );
    }
}

void MainWindow::editCustomGlyph()
{
    AddCustomGlyphDialog
        dialog;

    if( !characterViewWidget.tableView->selectionModel() )
    {
        return;
    }

    int row = characterViewWidget.tableView->selectionModel()->currentIndex().row();

    int unicode, start, advance, baseline;
    if( !project->getCustomCharacter( row, unicode, dialog.pixmap(), start, advance, baseline ) )
    {
        return;
    }

    dialog.unicode( unicode );
    dialog.start( start );
    dialog.advance( advance );
    dialog.baseline( baseline );

    if( dialog.exec() == QDialog::Accepted )
    {
        project->updateCustomCharacter( row, dialog.unicode(), dialog.pixmap(), dialog.start(), dialog.advance(), dialog.baseline() );
    }
}

void MainWindow::createActions()
{
    newAct = new QAction(QIcon(":/images/new.png"), tr("&New"), this);
    newAct->setShortcuts(QKeySequence::New);
    newAct->setStatusTip(tr("Create a new file"));
    connect(newAct, SIGNAL(triggered()), this, SLOT(newFile()));

    openAct = new QAction(QIcon(":/images/open.png"), tr("&Open..."), this);
    openAct->setShortcuts(QKeySequence::Open);
    openAct->setStatusTip(tr("Open an existing file"));
    connect(openAct, SIGNAL(triggered()), this, SLOT(open()));

    saveAct = new QAction(QIcon(":/images/save.png"), tr("&Save"), this);
    saveAct->setShortcuts(QKeySequence::Save);
    saveAct->setStatusTip(tr("Save the document to disk"));
    connect(saveAct, SIGNAL(triggered()), this, SLOT(save()));

    saveAsAct = new QAction(tr("Save &As..."), this);
    saveAsAct->setShortcuts(QKeySequence::SaveAs);
    saveAsAct->setStatusTip(tr("Save the document under a new name"));
    connect(saveAsAct, SIGNAL(triggered()), this, SLOT(saveAs()));

    exitAct = new QAction(tr("E&xit"), this);
    exitAct->setShortcuts(QKeySequence::Quit);
    exitAct->setStatusTip(tr("Exit the application"));
    connect(exitAct, SIGNAL(triggered()), this, SLOT(close()));

    aboutAct = new QAction(tr("&About"), this);
    aboutAct->setStatusTip(tr("Show the application's About box"));
    connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));

    exportToABCAct = new QAction(tr("Export to ABC..."), this);
    exportToABCAct->setStatusTip(tr("Export the texture and the glyph definition file to ABC format"));
    connect(exportToABCAct, SIGNAL(triggered()), this, SLOT(exportToABC()));
}

void MainWindow::createMenus()
{
    fileMenu = menuBar()->addMenu(tr("&File"));
    fileMenu->addAction(newAct);
    fileMenu->addAction(openAct);
    fileMenu->addAction(saveAct);
    fileMenu->addAction(saveAsAct);
    fileMenu->addSeparator();
    fileMenu->addAction(exportToABCAct);
    fileMenu->addSeparator();
    fileMenu->addAction(exitAct);

    editMenu = menuBar()->addMenu(tr("&Edit"));

    toolsMenu = menuBar()->addMenu(tr("&Tools"));

    menuBar()->addSeparator();

    helpMenu = menuBar()->addMenu(tr("&Help"));
    helpMenu->addAction(aboutAct);
}

void MainWindow::createDockWindows()
{
    QDockWidget
        * model_dock;
    QWidget
        * characterViewHostWidget;

    // LAYERS

    model_dock = new QDockWidget( tr( "Character Table Info" ), this );
    model_dock->setObjectName( "model_dock" );

    characterViewHostWidget = new QWidget( model_dock );
    characterViewWidget.setupUi( characterViewHostWidget );
    model_dock->setWidget( characterViewHostWidget );

    connect( characterViewWidget.removeButton, SIGNAL( clicked() ), this, SLOT( removeCurrentSelectedRows() ) );
    connect( characterViewWidget.addButton, SIGNAL( clicked() ), this, SLOT( addACharacter() ) );
    connect( characterViewWidget.addCustomButton, SIGNAL( clicked() ), this, SLOT( addACustomGlyph() ) );
    connect( characterViewWidget.editCustomButton, SIGNAL( clicked() ), this, SLOT( editCustomGlyph() ) );

    addDockWidget( Qt::RightDockWidgetArea, model_dock );
    toolsMenu->addAction( model_dock->toggleViewAction() );
}

void MainWindow::createToolBars()
{
    fileToolBar = addToolBar(tr("File"));
    fileToolBar->addAction(newAct);
    fileToolBar->addAction(openAct);
    fileToolBar->addAction(saveAct);
}

void MainWindow::createStatusBar()
{
    statusBar()->showMessage(tr("Ready"));
}

void MainWindow::readSettings()
{
    QSettings settings("Fishing Cactus", "font-shaker");
    QPoint pos = settings.value("pos", QPoint(200, 200)).toPoint();
    QSize size = settings.value("size", QSize(400, 400)).toSize();
    resize(size);
    move(pos);
}

void MainWindow::writeSettings()
{
    QSettings settings("Fishing Cactus", "font-shaker");
    settings.setValue("pos", pos());
    settings.setValue("size", size());
}

bool MainWindow::maybeSave()
{
    if ( 0 ) //isModified())
    {
        QMessageBox::StandardButton ret;
        ret = QMessageBox::warning(this, tr("Application"),
                     tr("The document has been modified.\n"
                        "Do you want to save your changes?"),
                     QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
        if (ret == QMessageBox::Save)
        {
            return save();
        }
        else if (ret == QMessageBox::Cancel)
        {
            return false;
        }
    }
    return true;
}

void MainWindow::loadFile(const QString &fileName)
{
    QFile file(fileName);
    if (!file.open(QFile::ReadOnly | QFile::Text))
    {
        QMessageBox::warning(this, tr("Application"),
                             tr("Cannot read file %1:\n%2.")
                             .arg(fileName)
                             .arg(file.errorString()));
        return;
    }

    QTextStream in(&file);
    
    #ifndef QT_NO_CURSOR
        QApplication::setOverrideCursor(Qt::WaitCursor);
    #endif

    if( project )
    {
        project->deleteLater();
    }

    project = new Project;
        
    if( project->load( file ) )
    {
        characterViewWidget.tableView->setModel( project );
        textureWidget->setModel( project );

        QItemSelectionModel * selectionModel = new QItemSelectionModel( project, this );

        textureWidget->setSelectionModel( selectionModel );
        characterViewWidget.tableView->setSelectionModel( selectionModel );
    }
    else
    {
        delete project;
        project = 0;
        characterViewWidget.tableView->setModel( 0 );
        textureWidget->setModel( 0 );
    }

    #ifndef QT_NO_CURSOR
        QApplication::restoreOverrideCursor();
    #endif

    setCurrentFile(fileName);
    statusBar()->showMessage(tr("File loaded"), 2000);
}

bool MainWindow::saveFile(const QString &fileName)
{
    QFile file(fileName);
    
    if (!file.open(QFile::WriteOnly | QFile::Text))
    {
        QMessageBox::warning(this, tr("Application"),
                             tr("Cannot write file %1:\n%2.")
                             .arg(fileName)
                             .arg(file.errorString()));
        return false;
    }

    QTextStream out(&file);
    
    #ifndef QT_NO_CURSOR
        QApplication::setOverrideCursor(Qt::WaitCursor);
    #endif
    
    project->save( file );
    
    #ifndef QT_NO_CURSOR
        QApplication::restoreOverrideCursor();
    #endif

    setCurrentFile(fileName);
    statusBar()->showMessage(tr("File saved"), 2000);
    return true;
}

void MainWindow::setCurrentFile(const QString &fileName)
{
    currentFile = fileName;
    setWindowModified(false);

    QString shownName = currentFile;
    if (currentFile.isEmpty())
    {
        shownName = "untitled.xml";
    }
    setWindowFilePath(shownName);
}

QString MainWindow::strippedName(const QString &fullFileName)
{
    return QFileInfo(fullFileName).fileName();
}
